package com.feige.service.impl;

import com.feige.constant.Constants;
import com.feige.entity.SecurityUser;
import com.feige.helper.MenuHelper;
import com.feige.pojo.Permission;
import com.feige.pojo.vo.FrontRouteVo;
import com.feige.service.IndexService;
import com.feige.service.PermissionService;

import com.feige.utils.TokenUtils;
import com.feige.utils.exception.CustomException;
import com.feige.utils.exception.user.CaptchaException;
import com.feige.utils.exception.user.UserDisableException;
import com.feige.utils.jwt.JwtInfo;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.redis.RedisUtils;;
import com.feige.utils.exception.user.CaptchaExpireException;
import com.feige.utils.exception.user.UserPasswordNotMatchException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class IndexServiceImpl implements IndexService {

    @Resource
    private PermissionService permissionService;


    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisUtils redisUtils;


    @Resource
    private TokenUtils tokenUtils;

    @Override
    public List<FrontRouteVo> getMenu(JwtInfo jwtInfo) {
        List<Permission> permissions = permissionService.selectPermissionByUserId(jwtInfo);
        return MenuHelper.build(permissions);
    }

    @Override
    public String login(String username, String password, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        //获取缓存中的验证码
        String captchaCode = (String)redisUtils.get(verifyKey);

        if (StringUtils.isEmpty(captchaCode)){
            throw new CaptchaExpireException();
        }
        //删除验证码
        redisUtils.del(verifyKey);
        if (!code.equalsIgnoreCase(captchaCode)){
            throw new CaptchaException();
        }
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));

        }
        catch (Exception e) {
            if (e instanceof BadCredentialsException){
                throw new UserPasswordNotMatchException();
            } else{
                throw new CustomException(e.getMessage());
            }
        }
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        //查看用户是被禁用
        if (securityUser.getCurrentUser().getStatus() == 0){
            throw new UserDisableException();
        }
        //把数据保存到缓存中
        tokenUtils.saveSecurityUserCache(securityUser);

        return JwtUtils.getJwtToken(new JwtInfo(securityUser.getCurrentUser().getId(), securityUser.getCurrentUser().getUsername(), securityUser.getCurrentUser().getNum()));
    }


}
